package cn.itsource.org.service.impl;

import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zj
 * @since 2022-11-29
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    /*
    * 添加employee之前 必須要添加logininfo
    *
    * */
    @Override
    public void add(Employee employee) {
        Logininfo logininfo = new Logininfo();

        /*调用Employee的初始方法*/
        initEmployee(employee);

        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.save(logininfo);
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);

        handleRelationShip(employee);
    }


    private void handleRelationShip(Employee employee) {
        employeeMapper.removeEmployeeRole(employee.getId());
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRoles());
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        employee.setPassword(MD5Utils.encrypByMd5(employee.getPassword() + salt));
        employee.setState(1);
    }
}
